package com.fp.m7.client.presenter;

import net.customware.gwt.presenter.client.EventBus;
import net.customware.gwt.presenter.client.widget.WidgetDisplay;
import net.customware.gwt.presenter.client.widget.WidgetPresenter;

import com.fp.m7.client.event.InfoEvent;
import com.fp.m7.client.event.InfoEventHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Inject;

/**
 * A presenter for handling background events: "InfoEvent's", which are displayed under the header bar in a timed
 * manner.
 * 
 * @author 7
 */
public class InfoPresenter extends WidgetPresenter<InfoPresenter.Display> {

    public interface Display extends WidgetDisplay {

        HasText getMessage();

        void setInfo();

        void setWarning();
        
        void setSuccess();

    }

    private HasWidgets container;

    private final Timer timer = new Timer() {
        @Override
        public void run() {
            container.clear();
            timer.cancel();
        }
    };

    @Inject
    public InfoPresenter(Display display, EventBus eventBus) {
        super(display, eventBus);
    }

    @Override
    protected void onBind() {
        eventBus.addHandler(InfoEvent.TYPE, new InfoEventHandler() {
            @Override
            public void onBackgroundEvent(InfoEvent backgroundEvent) {
                container.add(display.asWidget());
                display.getMessage().setText(backgroundEvent.getMessage());
                timer.schedule(backgroundEvent.getDelayMs());

                switch (backgroundEvent.getType()) {
                case INFO:
                    display.setInfo();
                    break;
                case WARNING:
                    display.setWarning();
                    break;
                case SUCCESS:
                    display.setSuccess();
                    break;
                }
            }
        });
    }

    @Override
    protected void onUnbind() {
    }

    @Override
    protected void onRevealDisplay() {
        if (container != null) {
            container.clear();
        }
    }

    public void setContainer(HasWidgets container) {
        this.container = container;
    }

}
